/*
 * minimax.cpp
 *
 *  Created on: Feb 6, 2012
 *      Author: benzun
 */

#include "minimax.h"
using namespace std;
minimax::minimax(int ply1)
{
	ply=ply1;
}

State *minimax::run_minimax(State *s,bool player)
{
	State *child;
	int value,v_best,m_best;
	vector<int> actions;



	if(s->terminalTest())
	{
		if(player)
			s->cost=1;

		else
			s->cost=-1;
				//init->cost=distance_h(init,-1)-distance_h(init,1);
		return(s);
	}
	else if(s->validActions().size()==0)
	{
		s->cost=0.5;
		return(s);
	}

	if(player)
		v_best=-1;
	else
		v_best=1;

	actions=s->validActions();

	for(int i=0;i<actions.size();i++)
	{
		child=do_action(s,actions[i]);
		child=run_minimax(child,player);
		value=child->cost;
				//cout<<i<<" "<<ply<<endl;
		if(player)
		{
			if(v_best<value)
			{
				v_best=value;
				//m_best=i;
			}

		}
		else
		{
			if(v_best>value)
			{
			v_best=value;
			//m_best=i;
			}

		}
				player=!player;
	}

	child->cost=v_best;
	return(child);
}

State *minimax::do_action(State *s,int col)
{
	State *next=new State(s);
	next->updateState(col,!next->player);
	return next;
}
minimax::~minimax() {
	// TODO Auto-generated destructor stub
}

